import {
  ImagePreview
} from 'vant';
import tool from "@/common/tool.js";
class Product {
  mixin = {
    data() {
      return {
        productInfo: {}, //商品信息
        bannerIndex: 0, //所在大图索引
        typeSelectArray: [],
        isCollection: false,
        //购物车提交参数
        carform: {
          id: "", //商品id
          aid: "", //提交的库存skuid,从商品skus里面匹配
          number: 1, //商品数量
        },
        comment: {
          product_id: "",
          page: 1,
          page_size: 20,
        },
        commentList: [], //评论列表
        commentLoading: true,
        proTotal: 0, //评论总数
        value: 1.8,
        buyColorHide: false, //购买字体是否深色
        showModel: false, //是否展开分类遮盖板
        bannerShowImg: "", //banner展示的图片
      }
    },
    async asyncData(that) {
      let canonical = "https://www.missyeah.com" + that.route.fullPath;
      let productInfo = {
        id: "",
        item_id: "",
        title: "", //标题
        imgs: [], //轮播海报图
        price: "", //价格
        discount_price: "",
        product_option: [], //库存信息
        content: "", //商品介绍信息
        inventory: 0, //库存数量
        seo_title: "",
        seo_keyword: "",
        seo_description: ""
      }
      let typeSelectArray = {}; //商品属性选中索引，默认全部0
      let res = await that.store.dispatch("menu/productInfo", {
        id: that.route.params.id
      });
      res.content = tool.clearEditInfo(res.content);
      if (res.product_option.props != undefined) {
        for (let i = 0; i < res.product_option.props.length; i++) {
          typeSelectArray[i] = 0;
        }
      }
      if (res.product_option.skus != undefined && res.product_option.skus.length != 0) {
        res.price = res.product_option.skus[0].price;
        res.discount_price = res.product_option.skus[0].discount_price;
      }
      let imgs = [];
      if (res.imgs) {
        for (let i = 0; i < res.imgs.length; i++) {
          imgs.push(res.imgs[i].url);
        }
        res.imgs = imgs;
      }
      let moreModal = false; //分类描述遮盖板是否出现
      if (res.content) {
        if (res.content.length > 2000) {
          moreModal = true;
        } else {
          moreModal = false;
        }
      }
      return {
        productInfo: res == undefined ? productInfo : res,
        typeSelectArray: typeSelectArray,
        canonical,
        moreModal
      }
    },
    head() {
      return {
        title: this.productInfo.title,
        meta: [{
            hid: "keywords",
            name: "keywords",
            content: this.productInfo.seo_keyword || 'missyeah',
          },
          {
            hid: "description",
            name: "description",
            content: this.productInfo.seo_description || 'missyeah',
          },
        ],
        link: [{
          rel: "canonical",
          href: this.canonical || 'https://www.missyeah.com',
        }, ],
      }
    },
    activated() {
      this.getComment();
    },
    mounted() {
      this.queryIsCollection();
      this.comment.product_id = this.productInfo.id;
      console.log(this.productInfo);
    },
    computed: {
      cartList() {
        return this.$store.state.menu.cartList;
      }
    },
    methods: {
      //购买按钮鼠标移出事件
      buyOut() {
        let p = 0;
        setTimeout(() => {
          this.buyColorHide = false;
          let timer = setInterval(() => {
            p += 2;
            this.$refs.buy1.style.left = "-" + p + "%";
            if (p >= 100) {
              clearInterval(timer);
            }
          }, 2);
        }, 2000)
      },
      //购买按钮鼠标经过事件
      buyOver() {
        let p = 100;
        if (this.buyColorHide == false) {
          let timer = setInterval(() => {
            p -= 2;
            this.$refs.buy1.style.left = "-" + p + "%";
            if (p <= 0) {
              clearInterval(timer);
            }
          }, 2);
          this.buyColorHide = true;
          this.buyOut();
        }
      },
      //查看更多
      clickSeemore() {
        this.moreModal = false;
      },
      //滑动切换banner
      bannerChange(index) {
        this.bannerIndex = index;
        this.bannerShowImg = "";
      },
      //点击切换banner
      clickStep(dis) {
        let scrollLeft = this.$refs.navPanel.scrollLeft; //元素左边距
        if (dis == -1) {
          //向左
          let timer = setInterval(() => {
            scrollLeft = scrollLeft - 10;
            this.$refs.navPanel.scrollLeft = scrollLeft;
            if (scrollLeft <= 0) {
              clearInterval(timer);
            }
          }, 1);
        } else {
          //向右
          let _scrollLeft = 10;
          let timer = setInterval(() => {
            _scrollLeft = _scrollLeft + 10;
            this.$refs.navPanel.scrollLeft = scrollLeft + _scrollLeft;
            if (_scrollLeft == 100) {
              clearInterval(timer);
            }
          }, 1);
        }
      },
      //选中属性
      selectAttribute(index1, index2) {
        this.typeSelectArray[index1] = index2;
        this.bannerShowImg = this.productInfo.product_option.props[index1].children[index2].imgs[0].url;
        let selectTypeSku = "";
        for (let key in this.typeSelectArray) {
          selectTypeSku += key + '_' + this.typeSelectArray[key];
        }
        let skus = this.productInfo.product_option.skus;
        for (let i = 0; i < skus.length; i++) {
          let _selectTypeSku = "";
          for (let j = 0; j < skus[i].ids.length; j++) {
            _selectTypeSku += skus[i].ids[j];
          }
          if (_selectTypeSku == selectTypeSku) { //匹配到sku
            this.productInfo.price = skus[i].price;
            this.productInfo.discount_price = skus[i].discount_price;
          }
        }
      },
      //点击大图
      clickBanner(img) {
        console.log(img);
        //if (this.isMobile) {
        if (Array.isArray(img)) {
          ImagePreview({
            images: img,
            closeable: true,
            showIndicators: true,
          });
        } else {
          ImagePreview({
            images: [img],
            closeable: true,
            showIndicators: true,
          });
        }
        //}
      },
      //添加购物车
      async addCart() {
        this.tips.startLoadingToast();
        let aid = "";
        let attribute_me = "";
        for (let key in this.typeSelectArray) { //计算已选属性aid
          aid += this.productInfo.product_option.props[key].children[this.typeSelectArray[key]].parent_id + "," + this.productInfo.product_option.props[key].children[this.typeSelectArray[key]].id + ";";
          attribute_me = this.productInfo.product_option.props[key].children[this.typeSelectArray[key]].name;
        }
        aid = aid.substring(0, aid.length - 1);
        if (this.isLogin) {
          this.carform.id = this.productInfo.id;
          this.carform.aid = aid;
          let res = await this.$store.dispatch("menu/addCart", this.carform);
          this.tips.closeToast();
          this.buyOut();
          if (res.code == 0) {
            this.$toast.success("Add shopping bag successfully");
            this.$store.commit("menu/setCartRefresh", true); //刷新购物车列表
            this.$store.dispatch("menu/cartList"); //获取购物车
          } else {
            this.$toast.fail(res.msg);
          }
        } else {
          let cartList = [];
          this.cartList.forEach(item => {
            cartList.push(item);
          });
          let obj = {};
          for (let key in this.productInfo) {
            obj[key] = this.productInfo[key];
          }
          obj['number'] = this.carform.number;
          obj['aid'] = aid;
          obj['attribute_me'] = attribute_me;
          obj['attribute_text'] = [attribute_me];
          cartList.push(obj);
          console.log(cartList);
          this.$store.commit('menu/setCartList', cartList); //保存购物车列表
          tool.setStorage("cartList", cartList);
          setTimeout(() => {
            this.tips.closeToast();
            this.$toast.success("Add shopping bag successfully");
          }, 1000)
        }
      },
      //检查是否登录，未登录跳转登陆
      chechIsLogin() {
        if (this.isLogin == false) {
          this.$router.push({
            path: "/login",
            query: {
              redirect: location.pathname,
            }
          });
          return false;
        } else if (this.isLogin) {
          return true;
        } else {
          return true;
        }
      },
      //查询是否已收藏商品
      async queryIsCollection() {
        if (this.isLogin) {
          let res = await this.$store.dispatch("menu/collectionUp", {
            id: this.productInfo.id
          });
          if (res.code == 0 && res.data != undefined) {
            this.isCollection = res.data.isCollectionUp;
          }
        }
      },
      //收藏商品
      async proCollection() {
        let bool = this.chechIsLogin();
        if (bool) {
          this.tips.startLoadingToast();
          let res = await this.$store.dispatch("menu/proCollection", {
            id: this.productInfo.id
          });
          this.tips.closeToast();
          if (res.code == 0) {
            this.isCollection = !this.isCollection;
            this.$store.dispatch("user/collectionList", {
              page: 1,
              page_size: 100000
            }); //获取收藏列表
          } else {
            this.$toast.fail(res.msg);
          }
        }
      },
      //商品评价列表
      async getComment() {
        this.commentLoading = true;
        let res = await this.$store.dispatch("menu/commentList", this.comment);
        this.commentLoading = false;
        let commentList = res.data.list;
        if (res.code == 0 && res.data != undefined) {
          for (let i = 0; i < commentList.length; i++) {
            if (commentList[i].file_id) {
              for (let j = 0; j < commentList[i].file_id.length; j++) {
                commentList[i].file_id[j] = commentList[i].file_id[j].file_url;
              }
            }
          }
          this.commentList = commentList;
          this.proTotal = res.data.paginatio.total;
        }
      },
      //评论换页
      pageChange(index) {
        this.comment.page = index;
        this.getComment();
      }
    },
  }
}
export default new Product();
